// 两个线程，实现交替打印 1～100
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex mutex;
std::condition_variable cond;

int num = 0;
bool flag = false;

void Print1(int threadid)
{
    for (int i = 0; i < 10; ++i)
    {
        // 加锁
        std::unique_lock<std::mutex> lock(mutex);
        if (flag)
        {
            cond.wait(lock);
        }
        std::cout << threadid << ":" << num << std::endl;

        ++num;
        flag = true;
        cond.notify_one();
    }
}
void Print2(int threadid)
{
    for (int i = 0; i < 10; ++i)
    {
        std::unique_lock<std::mutex> lock(mutex);
        if (!flag)
        {
            cond.wait(lock);
        }
        std::cout << threadid << ":" << num << std::endl;
        ++num;
        flag = false;
        cond.notify_one();
    }
}
int main()
{
    // 创建两个线程
    std::thread t1(Print1, 0);
    std::thread t2(Print2, 1);

    t1.join();
    t2.join();

    return 0;
}
